package com.mrs.job;

import com.mrs.entity.Article;
import com.mrs.service.ArticleService;
import com.mrs.utils.RedisCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * description: UpdateViewCountJob
 * date: 2022/8/13 12:50
 * author: MR.孙
 */
@Component
public class UpdateViewCountJob {

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private ArticleService articleService;

    //每隔一分钟把redis数据更新到数据库中
    @Scheduled(cron = "0 0/1 * * * ?")
    public void updateViewCount(){
        //获取redis中的浏览量
        Map<String, Integer> viewCountMap = redisCache.getCacheMap("article:viewCount");

        //将Map类型转换为集合类型,方便updateBatchByI方法调用
        List<Article> articles = viewCountMap.entrySet()
                .stream()
                //entrySet中每一个集合都是一个键值对对象
                //通过构造方法给Article的id,和浏览量赋值
                .map(entry -> new Article(Long.valueOf(entry.getKey()), entry.getValue().longValue()))
                .collect(Collectors.toList());


        //更新到数据库中
        articleService.updateBatchById(articles);

    }

}
